<?php

namespace App\Services;

use App\Common\Libs\Ali\OssClient;
use App\Consts\GlobalConst;
use App\Consts\GlobalUploadConst;
use App\Exceptions\Error;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

/**
 * @package App\Services
 * @see ShareService
 */
class ShareService extends BaseService
{

    /** @var $_repository */
    public $_repository;

    /**
     * DynamicService constructor.
     */
    public function __construct()
    {
        parent::__construct();
        $this->_repository = repository()->ShareRepository;
    }

    /**
     * @param $type
     * @return string
     */
    public function getUploadPath($type)
    {
        $path = '';
        if ($type == GlobalConst::TARGET_TYPE_ARTICLE) {
            $path = GlobalUploadConst::SHARE_ARTICLE;
        } elseif ($type == GlobalConst::TARGET_TYPE_NOTE) {
            $path = GlobalUploadConst::SHARE_NOTE;
        }
        return $path;
    }

    /**
     * @param Request $request
     * @param $type
     * @return \Illuminate\Http\JsonResponse|mixed
     */
    public function upload(Request $request, $type)
    {
        // 获取path
        $basePath = $this->getUploadPath($type);
        if (!$basePath) {
            return Error::handle('Path is invalid', 80201);
        }
        // 获取文件类型参数
        $file = $request->file('file');
        if (empty($file) || !$file->isValid()) {
            return Error::handle('File is invalid!',80202);
        }
        $ext = $file->getClientOriginalExtension();
        $path = $file->getRealPath();
        // 10 位时间戳 + 下划线 + 18 位随机字符串
        $fileName = $basePath.time().'_'.Str::random(18).".$ext";
        // 上传文件到 OSS
        try {
            $result = OssClient::getInstance()->putObject($fileName, $path);
            if (empty($result)) {
                return Error::handle('upload failed!',80203);
            }
            $result['result'] = basename($result['url']);
        } catch (\Exception $e) {
            return Error::handle($e->getMessage(), 80204);
        }

        return $result;
    }

}
